<?php 
/**
 * 用户相关操作模块
 * @author :zhulin 
 * @since:2012 5.24
 */
class User_Info{
    
     const TABLE_NAME = 'user_baseinfo';
     const TABLE_NAME_SEARCH = 'user_extendinfo';
     
     protected $uId;

     protected $_data;

      /**
         * 单例对象
      */
     public static $singletonObjects = array();
    /**
     * 缓存的KEY
     */
    protected $_cacheKey;

    /**
     * 缓存实例
     *
     * @var Helper_Cache_Memcache
     */
    protected $_cacheInstance;
     /**
      *  获取单例
      * @param type $uId 用户Id
      * @return 
      */
    /**
     * 缓存的命名空间
     */
    const CACHE_NS = '_userInfo';
    

      public static function getInstance( )
	{
		$className = __CLASS__;
		if( !isset( self::$singletonObjects[$className] ) )
		{
			self::$singletonObjects[$className] = new self( );
		}

		return self::$singletonObjects[$className];
	}
        
        /**
	 * 构造器
     *
     * @param int $uId
	 */
//	protected function __construct( $uId )
//	{
//            $this->uId = $uId;
//            $this->_cacheKey = $uId . self::CACHE_NS;
//            echo $this->_cacheKey;
//            $this->_cacheInstance = Common::getCache();
//            $this->_data = $this->_cacheInstance->get( $this->_cacheKey );
//
//            if( $this->_data === false )
//            {
//                $this->_loadFromDb();
//                $this->_saveToCache();
//            }
//
//            if( empty( $this->_data ) )
//            {
//                $this->_data = array();
//            }
//	}
       /**
        *  根据用户名和密码获得用户信息
        */
       public static function getUserInfo( $username,$password)
    {
        if( $username == ''|| $password == '' )
        {
            throw new AppException( 303 );
        }
                $replace = array(
            '[' => '/[',
            ']' => '/]',
            '%' => '/%',
            '_' => '/_',
        );
        $Uname = strtr( $username , $replace);
        $Password = strtr($password , $replace);
        $userInfo = Common::getMysql()->get( self::TABLE_NAME , array( 'name' => $username , 'passwd' => $password ) );
        return $userInfo;
    } 
    /**
     * 根据用户Id获取用户的基本信息
     * @param type $uId 
     */
    public static function getUserInfoByUId( $uId ){
        $userBaseInfo =  Common::getMysql()->get( self::TABLE_NAME , array( 'uId' => $uId ) );
        $userExtendInfo = Common::getMysql()->get( self::TABLE_NAME_SEARCH , array( 'uId' => $uId ) );
        
        $userInfo = array(
            'name'    => $userBaseInfo['name'],
            'email'   => $userBaseInfo['email'],
            'headPic' => $userBaseInfo['headPic'],
            'sex' =>$userExtendInfo['sex'],
            'mobile'=>$userExtendInfo['mobile'],
            'birth'=>$userExtendInfo['birth'],
            'addr'=>$userExtendInfo['addr']
            
        );
        return  $userInfo;
    }
 
     /**
     * 上传图片
     * 
     * @param string $content       图片内容
     * @param int $width            图片宽度
     * @param int $height           图片高度
     */
    public static function uploadImg( $content , $width = 0 , $height = 0 )
    {
        //图片助手类
        $imgHelper = Helper_Img::getInstance();

        //获取文件格式
        $imgType = $imgHelper->checkImgType( $content );

        //文件类型错误
        if( !$imgType )
        {
            throw new AppException( 2004 );
        }

        //生成70x70的头像
        $imgHelper->setSrcImg( $content , $imgType );
        $imgHelper->setDstImg();
        
        $width = empty( $width ) ? $imgHelper->src_w : $width;
        $height = empty( $height ) ? $imgHelper->src_h : $height;
        
        $picName = $imgHelper->createImg( $width , $height );

        //释放
        $imgHelper->destroyImg();
        
        return $picName;
    }
    /**
     * 用户账户注册
     */
     public static function userRegister( $username , $password , $email , $headPicInfo){
         //参数校验
        if( empty( $username ) || empty( $password ) || empty( $email ) || empty( $headPicInfo ) )
        {
             throw new AppException( 303 );
        }
        //验证用户是否已被注册
        if( self::emailIsExists( $email ) ){
            throw new AppException( 2000 , $email );
        }
        
        //密码长度验证
        $passwd = Helper_Validate::passwordCheck( $password );

         //加密密码
        $key = Common::getConfig( 'passEncrypt' );
        $passwdHash = Helper_String::password_hash( $password , $key );

         //用户初始信息
        $userInfo = array(
            'uId'     => Counter_Builder::getInstance()->getUniqueIdByKey( 'uId' ) ,
            'email'   => $email, 
            'name'    => $username ,
            'passwd'  => $passwdHash,
            'headPic' => $headPicInfo 
        );
        //添加用户信息到数据库
        $affectedRows = Common::getMysql()->add( self::TABLE_NAME ,$userInfo );
        if( $affectedRows < 1 )
        {
            throw new AppException( 1000 );
        }
        //返回用户信息
        return $userInfo;   
    }
    /**
     * 学员用户注册
     */
    public static function userRegisterExtend( $uid , $sex , $mobile , $birth , $addr , $registerTime  ){
      
          //用户初始信息
        $userInfo = array(
            'uId'    => $uid ,
            'sex'    => $sex, 
            'mobile' => $mobile ,
            'birth'  => $birth,
            'addr'   => $addr,
            'registerTime'=> $registerTime 
        );
        //添加用户信息到数据库
        $affectedRows = Common::getMysql()->add( self::TABLE_NAME_SEARCH ,$userInfo );
        if( $affectedRows < 1 )
        {
            throw new AppException( 1000 );
        }
        //返回用户信息
        return $userInfo;   
        
        
    }
    /**
 * 上传图片
 */
    public static function imgUpload( $files , $path , $newWidth , $newHeight ){
        $pName = Helper_File::getInstance()->uploadBySize( $files , $path , $newWidth , $newHeight );
        return $pName;
        
    }
   
    /**
     * 判断用户设置的邮箱是否存在
     *
     * @param string    $email
     * @return  boolean
     */
    public static function emailIsExists( $email ){
        if( empty( $email ) ) {
            throw new AppException( 303 );
        }
        //邮箱地址过滤
       $email = Helper_Validate::emailCheck( $email );

        //根据邮箱查找用户
        $count = Common::getMysql()->getCount( self::TABLE_NAME , array( 'email' => $email ) );
        return $count ? true : false;
    }
    /**
     * 更新用户密码
     * 
     * @param array $info
     * @return array
     */
    public function updateUserPass( $info = array() )
    {
       if( empty( $info ) || !is_array( $info ) )
       { 
          throw new AppException( 303 );
       }
        //密码处理
        if( !empty( $info['passwd'] ) )
        {
            //密码长度验证
            $info['passwd'] = Helper_Validate::passwordCheck( $info['passwd'] );
        
            //密码加密
            $key = Common::getConfig( 'passEncrypt' );
            $info['passwd'] = Helper_String::password_hash( $info['passwd'] , $key );
           // unset( $info['passwd'] );
        }
        foreach( $info as $key => $val )
        {
           $this->_data[$key] = $val;
        }
       
        //保存到数据库
       $affectedRows = Common::getMysql()->update( self::TABLE_NAME , array( 'uId' => $_SESSION['uId'] ) , $info );
        
        //更新信息失败
        if( !$affectedRows )
        {
            throw new AppException( 1000 );
        }
        return $this->_data;
    }
    /**
     * 更新用户资料
     */
    public function updateUserInfo( $userBaseInfo ,$usereExtendInfo){
          if( empty( $userBaseInfo )||empty( $usereExtendInfo) || !is_array( $userBaseInfo ) || !is_array( $usereExtendInfo ) )
       { 
          throw new AppException( 303 );
       }
       //保存到user_baseinfo
       $affectRows1 = Common::getMysql()->update( self::TABLE_NAME , array( 'uId' => $_SESSION['uId']) ,$userBaseInfo );
       //保存到user_extendinfo 
       $affectRows2  = Common::GetMysql()->update( self::TABLE_NAME_SEARCH , array( 'uId'=> $_SESSION['uId']) , $usereExtendInfo) ;
         if( !$affectRows1 || $affectRows2 )
        {
            throw new AppException( 1000 );
        }
        
    }
    /**
     * 修改用户扩展表
     * @param type $lastLogin
     */
    public function updateUserExtend( $dataArr ){
        if( !is_array ( $dataArr)){
            throw new AppException ( 303);  
        }
        $affectRow = Common::getMysql()->update( self::TABLE_NAME_SEARCH , array( 'uId' =>$_SESSION['uId']) , $dataArr);
        if( !$affectRow){  
            throw new AppException( 1000 );
        }
        
    }
    /**
     * 用户选择课程，记录mc
     * @param type $dataArr 
     */
    public function selectCourse( $dataArr){
        
        if( !is_array ( $dataArr)){
            throw new AppException ( 303 );  
        }
        $affectRow = Common::getMysql()->update( self::TABLE_NAME_SEARCH , array( 'uId' =>$_SESSION['uId']) , $dataArr);
        if( !$affectRow){  
            throw new AppException( 1000 );
        }
        
        // 写入mc
//        $course = array();
//        $userCourse = Common::getCache()->get('user');
//        $userCourse[$_SESSION['uId']] = array(  $lessonId , $testId );
//        Common::getCache()->set('userCourse', $userCourse);
        
    }
  
    /**
     * 获取用户密码信息
     * @return string
     */
    public function getInfoUserPasswd( $uId )
    {
       
        $userInfo = common::getMysql()->get( self::TABLE_NAME , array( 'uId' => $uId ));
        return $userInfo['passwd'];
        //return $this->_data['passwdHash'];
    }
    
    /**
     * 从数据库加载用户的基本信息
     * @return array
     */
    private function _loadFromDb()
    {
        //获取用户基本信息
		$userInfo = Indexer::getInstance( $this->uId )->getDb()->get( self::TABLE_NAME , array( 'uId' => $this->uId ) );

        if( $userInfo == false )
        {
            throw new AppException( 5 );
        }
        
        $this->_data = self::formatLngLat( $userInfo );
    }
 /**
  *　获得用户基本信息
  * @return　array() 
  */
    public function userBaseList(){
        $studentInfo = Common::getMysql()->getList( self::TABLE_NAME , 1 );
        return $studentInfo;
        
    }
    /**
     * 获取用户扩展信息
     * @param type $uid
     * @return array() 
     */
    public function userExtendList( $uid ){
        
        $studentInfo = Common::getMysql()->get( self::TABLE_NAME_SEARCH , array( 'uId' => $uid ));
        return $studentInfo;
    }
    /**
     * 存储数据到cache
     */
    private function _saveToCache()
    {
        $this->_cacheInstance->set( $this->_cacheKey , $this->_data );
    }
   /*
     * 获取cache实例
     */

    public function _getCache() {

        return Common::getCache();
    }

    /*
     * 获取db实例
     */

    public function _getMysql() {

        return Common::getMysql();
    }

    /*
     * 添加Cache
     * 
     */

    public function addCache ( $arr ) {

        $this->_cacheInstance->add(self::CACHE_NS, $arr);
    }

    /*
     * 获取cache
     */

    public function getCacheValue($cache_ns) {

        return $this->_cacheInstance->get($cache_ns);
    }

    
}